import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
import { loginData } from '../api/Login';
import { auth } from '../Components/Auth';
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';

const request = axios.create({
  baseURL: "https://api-harmony-teach.itheima.net/hm/",
  timeout: 20000
})
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const user=auth.getUser()
  if(user.token){

    // config.headers.Authorization=String(token)
    // config.headers.Authorization="Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJpYXQiOjE3MzI1MzEwNzAsImV4cCI6MTczMjUzNDY3MH0._lIufSu0ZFIE4UZsHxFLEY5M18wlU20XqkFAlE2oPGs"
    // config.headers.token=token
    config.headers.Authorization="Bearer "+user.token
  }else{
    router.pushUrl({
      url:"pages/Login",

    },router.RouterMode.Single)
    promptAction.showToast({
      message:"登录失效"
    })
  }
  console.log(config.headers.token)
  return config
})
request.interceptors.response.use((response: AxiosResponse) => {
  if (response.data.code == 10000) {
    return response.data
  }else if(response.status == 401){
    auth.setUser({} as loginData)
    router.pushUrl({
      url:"pages/Login",

    },router.RouterMode.Single)
    promptAction.showToast({
      message:"登录失效"
    })

  }
  else {
    return response.data
    return Promise.reject(response.data.msg)
  }
},
  (error: AxiosError) => {
    return Promise.reject(error.message)
  }
)

export default class Http {
  get<T>(url: string, params?: object) {
    return request.get<null, T>(url, {
      params
    })
  }

  post<T>(url: string, data?: object) {
    return request.post<null, T>(url, data)
  }

  put<T>(url: string, data?: object) {
    return request.put<null, T>(url, data)
  }

  delete<T>(url: string, params?: object) {
    return request.delete<null, T>(url, {
      params
    })
  }
}
export const http = new Http()